<?php

class AdminController extends Controller {

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('index', 'delete', 'report', 'view', 'create', 'update', 'sort', 'sendemail', 'reply','option'),
                //'users' => UserIdentity::getAccessUser(5),
                'users' =>  array('veniceq'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionIndex() {
 
 
        if(isset($_POST['option'])){
            
            foreach($_POST['option'] as $row=>$value){
            $model = OptionModel::model()->findByPk($row);
            $model->option_value = $value;
            $model->update();
            }
            
        }        
        $modules = OptionModel::getOptionByType('modulelist');
        $theme = OptionModel::getOptionByType('themesmain');
               

        $this->render('index', array('modules' => $modules,'theme'=>$theme));
    }

    public function actionReport() {
        $name = $_GET['model'];
        $namemodel = ucfirst($name) . "Model";
        $renders = $name . "/admin";
        $model = new $namemodel('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET[$namemodel]))
            $model->attributes = $_GET[$namemodel];

        $this->render($renders, array(
            'model' => $model,
        ));
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id, $model) {
        $namemodel = ucfirst($model) . "Model";
        
        if($namemodel=='ContactModel'){
        $data = ContactModel::model()->findByPK($id);
        $data->status = 'read';
        $data->update();
        }
        
        $renders = $model . "/view";
        $this->render($renders, array(
            'model' => Common::loadModelByPK($id, $namemodel),
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $models = $_GET['model'];
        $namemodel = ucfirst($models) . "Model";
        $view = $models . "/view";
        $update = $models . "/update";
        $model = Common::loadModelByPK($id, $namemodel);

        if (isset($_POST[$namemodel])) {
            $model->attributes = $_POST[$namemodel];
            if ($models == "post") {
                $model->post_name = Common::buildSlug($_POST['PostModel']['title']);
                $model->post_url = "/home/" . $model->post_name;
            }
            if ($model->save())
                $this->redirect(array('/admin/report/?model=' . $models));
        }

        $this->render($update, array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $models = $_GET['model'];
            $namemodel = ucfirst($models) . "Model";
            //$this->loadModel($id)->delete();
            $model = Common::loadModelByPK($id, $namemodel)->delete();
            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $models = $_GET['model'];
        $namemodel = ucfirst($models) . "Model";
        $model = new $namemodel;


        if (isset($_POST[$namemodel])) {
            $model->attributes = $_POST[$namemodel];
            if ($models == "post") {
                $model->post_name = Common::buildSlug($_POST['PostModel']['title']);
                $model->post_url = "/home/" . $model->post_name;
              
            }
            if ($model->save()){
                  if(isset($_POST['option'])){
                    foreach($_POST['option'] as $key=>$value){
             if(!empty($value)){
                        $option = new OptionModel;
                      
                        $option->option_name= $key;
                        $option->option_value = $value;
                        $option->option_type = 'postoption';
                        $option->object_id = $model->id;
                        
                        $option->save();
                    }}
    
                }
                $this->redirect(array('/admin/report/?model=' . $models));
            }
        }

        $this->render($models . '/create', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'menu-model-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionSort() {
        if (isset($_POST['items']) && is_array($_POST['items'])) {
            $i = 0;
            foreach ($_POST['items'] as $item) {
                $project = MenuModel::model()->findByPk($item);
                $project->menu_order = $i;
                $project->save();
                $i++;
            }
        }
    }
    
    public function actionReply(){
        
        $id=$_POST['id'];
        $model = ContactModel::model()->findByPk($id);
        
        if(isset($_POST['subject']))
            {
            $subject = $_POST['subject'];
            $body = $_POST['message'];
            $email = $model->email;
           
            SendMail::sendGmailReply($subject, $body, $email);
            
            $reply = ContactModel::model()->findByPk($id);
            $reply->status = 'reply';
            $reply->update();
            
            $this->redirect('report/?model=contact');
        }
        
        
        $model->subject = 'Reply :: '.$model->subject;
        $message = '<div>'.'Reply :: '.'<div>';
        $message .= '<br>';
        $message .= '<br>';
        $message .= '<br>';
        $message .= '<div>'.'----------------------------------------------------------------------------------'.'</div>';
        $message .= '<div>'.'From :: '.$model->name.' Date :: '.$model->contact_date.'</div>';
        $message .= '<div>'.'----------------------------------------------------------------------------------'.'</div>';
        $message .= '<div>'.$model->message.'</div>';
        $model->message = $message;
        
        
        
        $this->render('reply_contact',array('model' => $model));
    }
    public function actionOption(){
        $model=new OptionModel('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['OptionModel']))
			$model->attributes=$_GET['OptionModel'];

		$this->render('option/admin',array(
			'model'=>$model,
		));
    }
     

}